/**
 * Created by Noir on 1/10/14.
 */
'use strict'
define([],function(){
    // must be a provider since it will be injected into module.config()
    var routeResolver = function(){
        this.$get = function(){
            return this;
        };

        this.routeConfig = function(){
            var viewsDirectory = './partials/',
                controllersDirectory = '/js/controller/',
                setBaseDirectories = function(viewsDir, controllersDir){
                    viewsDirectory = viewsDir;
                    controllersDirectory = controllersDir;
                },
                getViewsDirectory = function(){
                    return viewsDirectory;
                },
                getControllersDirectory = function(){
                    return controllersDirectory;
                };

            return{
                setBaseDirectories: setBaseDirectories,
                getControllersDirectory: getControllersDirectory,
                getViewsDirectory: getViewsDirectory
            };
        }();

        this.route = function(routeConfig){
            var resolve = function(templateUrl, controllerUrl, controllerName){
                var routeDef = {};
                routeDef.templateUrl = routeConfig.getViewsDirectory() + templateUrl;
                routeDef.controller = controllerName;
                routeDef.resolve = {
                    load: ['$q','$rootScope', function($q, $rootScope){
                        var dependencies = [routeConfig.getControllersDirectory() + controllerUrl];
                        return resolveDependencies($q, $rootScope, dependencies);
                    }]
                };

                return routeDef;
                },
                resolveDependencies = function($q, $rootScope, dependencies){
                    var defer = $q.defer();
                    require(dependencies, function(){
                        defer.resolve();
                        $rootScope.$apply();
                    });

                    return defer.promise;
                };

            return {
                resolve: resolve
            }
        }(this.routeConfig);
    };

    var servicesApp = angular.module('routeResolverServices',[]);

    servicesApp.provider('routeResolver', routeResolver);
})